package tpalgo3.vista.sprites;

import java.awt.Color;
import java.awt.Dimension;
import java.util.Observable;
import java.util.Observer;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;

import org.apache.log4j.Logger;

import tpalgo3.modelo.enemigos.Cucaracha;
import tpalgo3.vista.Tablero;
import tpalgo3.vista.util.VistaUtil;

import com.jgoodies.forms.layout.CellConstraints;

public class CucarachaVista extends JPanel implements Observer {
	private static final long serialVersionUID = 7853809840589853934L;
	private static final Logger logger = Logger.getLogger(CucarachaVista.class);
	private static final String PATH_ICONO = "img/cucaracha2.gif";
	
	private int equis;
	private int igriega;
	private Tablero tablero;
	private Cucaracha model;
	private JLabel iconoLabel;
	
	public CucarachaVista(Cucaracha cucaracha) {
		this.model = cucaracha;
		ImageIcon icono = VistaUtil.createImageIcon(PATH_ICONO);
		this.setPreferredSize(new Dimension(35, 35));
		this.setBackground(Color.WHITE);
		iconoLabel = new JLabel();
		iconoLabel.setIcon(icono);
		this.add(iconoLabel);
		cucaracha.addObserver(this);
		this.setVisible(true);
	}
	
	@Override
	public void update(Observable arg0, Object arg1) {
		if (model.isFueraDelTablero()) {
			CucarachaVista.this.setVisible(false);
		} 
		else if (!model.tieneResistencia()) {
			CucarachaVista.this.setVisible(false);
			equis = (int)model.getPosicion().getX();
			igriega = (int)model.getPosicion().getY();
			Explosion e = new Explosion();
			tablero.add(e, new CellConstraints().xy(equis + 1, igriega + 1));
			tablero.validate();
			try {
				Thread.sleep(200L);
			} catch (InterruptedException e1) {
				logger.error("Error por Thread.sleep() ", e1);
			}
			tablero.add(Explosion.quitarExplosion(equis, igriega), new CellConstraints().xy(equis + 1, igriega + 1));
			tablero.validate();
		}
		else {
			equis = (int)model.getPosicion().getX();
			igriega = (int)model.getPosicion().getY();
			tablero.add(this, new CellConstraints().xy(equis + 1, igriega + 1));
			tablero.validate();
		}
	}

	public Tablero getTablero() {
		return tablero;
	}

	public void setTablero(Tablero tablero) {
		this.tablero = tablero;
	}
}